const { query, body, param } = require('express-validator')
const { validResultCallback } = require('../../middleware')
const { validInt, validReg } = require('../../utils/validator')

const getRolesValidator = [
  validInt(query, 'page'),
  validInt(query, 'limit'),
  validReg(query, 'status', /^[01]$/),
  validResultCallback
]

const createRoleValidator = [
  body('menus', 'menus 格式错误')
    .isArray()
    .bail()
    .custom(arr => !arr.some(v => typeof v !== 'number' || /[^\d]/.test(v))),
  body('status')
    .exists()
    .withMessage('status 未传')
    .bail()
    .custom(value => [0, 1].includes(value))
    .withMessage('status 格式错误'),
  body('name')
    .exists({ checkFalsy: true })
    .withMessage('name 未传'),
  validResultCallback
]

const updateRoleValidator = [
  body('menus', 'menus 格式错误')
    .isArray()
    .bail()
    .custom(arr => !arr.some(v => typeof v !== 'number' || /[^\d]/.test(v))),
  body('status')
    .exists()
    .withMessage('status 未传')
    .bail()
    .custom(value => [0, 1].includes(value))
    .withMessage('status 格式错误'),
  body('name')
    .exists({ checkFalsy: true })
    .withMessage('name 未传'),
  validResultCallback
]

const statusValidator = [
  param('status')
    .exists()
    .withMessage('status 未传')
    .bail()
    .custom(value => ['0', '1'].includes(value))
    .withMessage('status 格式错误'),
  validResultCallback
]

module.exports = {
  getRolesValidator,
  createRoleValidator,
  updateRoleValidator,
  statusValidator
}
